<template>
  <div>
    <n-grid :x-gap="5">
      <n-grid-item :span="16">
        <n-card  title="上传图片" bordered style="height: 300px">
          <template #header-extra>
            <n-button size="small" type="warning" style="margin-left: 5px;" @click="resetImg"> 清除</n-button>
          </template>
          <n-space justify="center">
            <div class="canvas-wrapper">
              <n-image
                  ref="img2img_imgRef"
                  :height="220"
                  :object-fit="'scale-down'"
                  v-if="describeVo.base64Image"
                  :src="describeVo.base64Image"
                  alt=""/>
            </div>
            <n-empty description="未上传图片" v-if="!describeVo.base64Image">
              <template #extra>
                <n-upload
                    :custom-request="customRequest"
                >
                  <n-button>上传图片</n-button>
                </n-upload>
              </template>
            </n-empty>
          </n-space>
        </n-card>
      </n-grid-item>
      <n-grid-item :span="8">
        <n-card title="反推" bordered>
           <n-form size="small">
             <n-form-item label-placement="top" label="反推类型">
               <n-select size="small" :options="describeModelOption" v-model:value="describeVo.type"></n-select>
             </n-form-item>
             <n-button type="primary" block :loading="describeLoading" @click="describeImage">反推</n-button>
           </n-form>
        </n-card>
      </n-grid-item>
    </n-grid>

  </div>
</template>

<script setup lang="ts">

import {UploadCustomRequestOptions} from "naive-ui";
import {ref} from "vue";
import {fooocusControllerApi} from "@/api/paint/fooocusController.api";
import {fooocusDict} from "@/dictionary/fooocusDict";

const {describeModelOption} =  fooocusDict()
const describeLoading = ref(false)

const props = defineProps({
  resourceId: {
    type: String,
    default: '',
    required: true
  },
  descriptionFunction: {
    type: Function,
    required: false
  }
})

const describeVo = ref({
  resourceId: props.resourceId,
  type: 'Anime',
  base64Image: null
})




const customRequest = (uploadOption: UploadCustomRequestOptions) => {
  const reader = new FileReader();
  //@ts-ignore
  reader.readAsDataURL(uploadOption.file.file);
  reader.onloadend = () => {
    let image = new Image()
    image.src = reader.result
    //@ts-ignore
    describeVo.value.base64Image = reader.result
  };
}


const resetImg = () => {
  describeVo.value.base64Image = ''
}


const describeImage = ()=>{
  describeLoading.value = true
  const describeVoInput = {
    ...describeVo.value
  }
  describeVoInput.base64Image = describeVoInput.base64Image.split(',')[1]
  fooocusControllerApi.describe(describeVoInput).then(res=>{
    if(res.code === 200){
      if(props.descriptionFunction){
        props.descriptionFunction(res.data)
      }
    }
  }).finally(()=>{
    describeLoading.value = false
  })
}




</script>
